package mstest.wechat.controller;

import lombok.extern.slf4j.Slf4j;
import mstest.wechat.base.config.Constant;
import mstest.wechat.base.config.ResponseCode;
import mstest.wechat.base.exp.BizException;
import mstest.wechat.base.util.HttpReqUtil;
import mstest.wechat.base.util.wechat.WXUtil;
import mstest.wechat.base.util.string.ObjectTranslate;
import mstest.wechat.base.util.string.StringUtil;
import mstest.wechat.bean.BindBean;
import mstest.wechat.bean.TemplateData;
import mstest.wechat.bean.WechatParamBean;
import mstest.wechat.entity.UserRela;
import mstest.wechat.service.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: wechat
 * File Name: WechatController
 * Package Name: mstest.wechat.controller
 * Date: 2018/7/26  15:16
 * Copyright (c) 2018, tianyul All Rights Reserved.
 */
@RestController
@Slf4j
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WechatService wechatService;

    /**
     * 获取token
     * @return
     */
    @RequestMapping("/getToken")
    public UserRela getToken(@RequestBody WechatParamBean wechatParamBean) {
        //第一次或者清除缓存了，需要用code获取信息
        if(StringUtil.isEmpty(wechatParamBean.getOpenid())) {
            //校验code
            if(StringUtil.isEmpty(wechatParamBean.getCode())) {
                throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "code错误");
            }
            //获取用户相关信息
            Map<String,Object> result = WXUtil.getAccessToken(wechatParamBean.getCode());
            if(result.containsKey("errorcode")) {
                throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, ObjectTranslate.getString(result.get("errmsg")));
            }

            //access token
            String accessToken = ObjectTranslate.getString(result.get("access_token"));

            //失效事件 7200秒
            Long expiresIn = ObjectTranslate.getLong(result.get("expires_in"), 0L);

            //刷新access token 用的
            String refreshToken = ObjectTranslate.getString(result.get("refresh_token"));

            //用户再次公众号的唯一标识
            String openid = ObjectTranslate.getString(result.get("openid"));

            //授权作用域
            String scope = ObjectTranslate.getString(result.get("scope"));

            //记录openid  accessToken   失效时间
            return wechatService.save(openid, accessToken, expiresIn, refreshToken);
        }
        String openid = wechatParamBean.getOpenid();
        return wechatService.getUserInfo(openid);
    }

    /**
     * 绑定信息
     * @param bindBean
     */
    @PostMapping("/bind")
    public void bind(@RequestBody BindBean bindBean) {
        if(StringUtil.isEmpty(bindBean.getOpenid())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "用户id不能为空");
        }
        if(StringUtil.isEmpty(bindBean.getCardNo())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "证件号不能为空");
        }
        if(StringUtil.isEmpty(bindBean.getUserName())) {
            throw new BizException(ResponseCode.PARAM_ILLEGAL_ERROR, "账号不能为空");
        }
        wechatService.bind(bindBean);
    }

    /**
     * 发送模板消息
     * @param bindBean
     * @return
     */
    @PostMapping("/template/send")
    public String sendTemplate(@RequestBody BindBean bindBean) {
        //TODO 获取accessToken
        //TODO 获取openid
        String openid = "";
        //TODO 根据openid获取存储的accesstoken（如果失效，去refresh ，如果refresh不行，就返回错误，用户30内未登录）
        String accessToken = "";

        //使用accessToken 去发送目标消息
        String url = Constant.template_url+"?access_token="+accessToken;
        TemplateData templateData = new TemplateData();
        templateData.setTouser(openid);//openid
        templateData.setTemplate_id("111111");//TODO 模板id
        templateData.setUrl("");//TODO 跳转连接
        templateData.setMiniprogram("");

        Map<String,Object> data = new HashMap<>();

        Map<String,Object> first = new HashMap<>();
        first.put("value", "哈哈哈");
        first.put("color", "#173177");

        Map<String,Object> keyword1 = new HashMap<>();
        keyword1.put("value", "keyword1");
        keyword1.put("color", "#173177");

        Map<String,Object> keyword2 = new HashMap<>();
        keyword2.put("value", "keyword2");
        keyword2.put("color", "#173177");

        data.put("first", first);
        data.put("keyword1", keyword1);
        data.put("keyword2", keyword2);

        templateData.setData(data);

        Map<String, Object> result = HttpReqUtil.post(url, templateData);
        if("0".equals(ObjectTranslate.getString(result.get("errcode")))) {
            return "success";
        }
        return "fail";
    }


}
